package com.wqiuqiu.gulimall.secdkill.controller;


import com.wqiuqiu.common.R;
import com.wqiuqiu.common.to.login.MemberResponseTo;
import com.wqiuqiu.common.to.mq.SecdKillOrderTo;
import com.wqiuqiu.gulimall.secdkill.interceptor.SecdkillInterceptor;
import com.wqiuqiu.gulimall.secdkill.service.SecdKillService;
import com.wqiuqiu.gulimall.secdkill.to.SecdKillRedisTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class SeckillController {

    @Autowired
    SecdKillService secdKillService;
    @Autowired
    SecdkillInterceptor secdkillInterceptor;

    @ResponseBody
    @GetMapping("/currentSeckillSessions")
    public R currentSeckillSessions(){

        List<SecdKillRedisTo> sessions = secdKillService.getCurrentSeckillSessions();
        return R.ok().setData(sessions);
    }
    @ResponseBody
    @GetMapping("/{skuId}")
    public R getSecdKillInfoBySkuId(@PathVariable("skuId") Long skuId){

        //TODO 一个商品是否同时存在两个秒杀活动
        SecdKillRedisTo data = secdKillService.getSecdKillInfoBySkuId(skuId);
        return R.ok().setData(data);

    }
    @GetMapping("/kill/sku")
    public String kill(@RequestParam("killId") String killId, @RequestParam("code") String code, @RequestParam("num") int num,
                       Model model){

        //判断是否登录
        MemberResponseTo memberResponseTo = SecdkillInterceptor.threadLocal.get();
        if (memberResponseTo == null){
            return "redirect:http://auth.gulimall.com/login.html";
        }
        SecdKillOrderTo to = secdKillService.kill(code,killId,num);
        model.addAttribute("order",to);
        return "success";
    }
}
